/*
 * @Descripttion: 封装socket方法
 * @version: 1.0
 * @Date: 2024-01-22 17:03
 * @LastEditTime: 2024-01-22 18:00
 * @params: 
 *  -type: xuxie（续写）、fanyi（翻译）
 *  -content: 文本
 */

import appConfig from '@/config/index'
import { type BaseResult } from '@/api/base'

export interface aiResult extends BaseResult {
  temp: any
  data: any
}

export const aiSocket = (type: string, content: string | any) => {
  const connectURL = `${appConfig.api.websocketUrl}/aiEvent`;
  let websocket: any;

  return new Promise<string>((resolve, reject) => {
    // 提交参数
    let text = type === 'xuxie' ? `${content}。请帮我续写这段话`
             : type === 'fanyi' ? `${content}。请帮我把这段话翻译成英语，并返回英语`
             : type === 'code' ? content
             : '';

    const submitData = {
      event: 'aiEvent', // websocket的后端接口
      data: text
    }

    websocket = new WebSocket(connectURL);

    websocket.onopen = (e: object) => {
      sendWs(submitData);
    }

    websocket.onmessage = (e: any) => {
      let jsonData = JSON.parse(e.data);
      resolve(jsonData)
      websocket.close()
    }

    websocket.onclose = (e: object) => {
      console.log('关闭websocket', e)
    }

    websocket.onerror = (e: object) => {
      console.log('websocket错误', e)
      reject(e);
    }

    const sendWs = (data: object) => {
      websocket.send(JSON.stringify(data))
    }

  })
}

export const aiDialogSocket = (content: string | any) => {
  const connectURL = `${appConfig.api.websocketUrl}/aiEvent`;
  let websocket: any;

  return new Promise<string>((resolve, reject) => {
    // 提交参数
    const submitData = {
      event: 'aiEvent', // websocket的后端接口
      data: content
    }

    websocket = new WebSocket(connectURL);

    websocket.onopen = (e: object) => {
      sendWs(submitData);
    }

    websocket.onmessage = (e: any) => {
      let jsonData = JSON.parse(e.data);
      resolve(jsonData)
      websocket.close()
    }

    websocket.onclose = (e: object) => {
      console.log('关闭websocket', e)
    }

    websocket.onerror = (e: object) => {
      console.log('websocket错误', e)
      reject(e);
    }

    const sendWs = (data: object) => {
      websocket.send(JSON.stringify(data))
    }

  })
}
